"""
@Project ：HD_project 
@File    ：tem_plan.py
@IDE     ：PyCharm 
@Author  ：靓仔
@Date    ：2023/12/13 0013 9:08 
"""
import json
from urllib.parse import urljoin
from api_requests.temporary_plan.config import TODO_PLAN_ACTIVITY_DICT, HEADERS, session_request, session_login

todo_plan_activity_dict = {"zdgl_zdjh_nwzb_bmnbsh": "部门内审核", "zdgl_zdjh_nwzb_bmfzrsh": "部门负责人审核",
 "zdgl_zdjh_nwzb_fgbsp": "法规部审批核", "zdgl_zdjh_nwzb_fgbsh": "法规部审核", "zdgl_gzzd_nwzb_fgbsd": "法规部审定"}


class JapdApi:
    BASE_URL = "http://10.6.10.110/"

    # 初始化流程，写入缓存，避免重复调用接口
    def __init__(self):
        self.session = session_request
        self.user_id = session_login()
        self.get_pant = self.get_pant_info()
        self.todo_id = self.get_temporary_plan_id()
        self.todo_by_todo_id = self.query_todo_by_todo_id()
        self.next_activit = self.get_next_plan_info()

    # 获取当前用户下的所有待办信息
    def get_pant_info(self):
        _url = urljoin(self.BASE_URL, "bd-grsx-api/todo/page/collapse")
        data = {"bllx": "2", "userId": self.user_id, "xtbs": "10011006"}
        res = json.loads(self.session.post(url=_url, json=data, headers=HEADERS).text)
        return res

    # 获取所有todoID
    def get_temporary_plan_id(self):
        todo_id_list = []
        if self.get_pant["result"]:
            for tem_plan_id in self.get_pant["result"]:
                for todo_id in tem_plan_id["datas"]["list"]:
                    todo_id_list.append(todo_id["id"])
        else:
            return None
        return todo_id_list

    # 提交临时计划部门内审核
    def bmnsh_plan(self):
        if self.todo_id:
            for todo in self.todo_id:
                url = urljoin(self.BASE_URL, "zdgl-api/common/submit")
                data = {"xtbs": "10011006", "docType": "4", "data": {"nextParticipantMap": {f"{self.next_activit}_user": [
                    {"id": self.user_id, "name": "颜值", "typeCode": "person", "bllx": "2",
                     "role": "主办部门负责人", "dblx": ""}]}, "nextActivityDefId": self.next_activit, "spyj": "",
                    "spjg": "1", "operateType": "2",
                    "todoId": todo, "sfyy": "1",
                    "extend": "{\"bmhqList\":[]}", "ywbs": "100",
                    "sccldry": "", "pbzlc": ""}}
                res = json.loads(self.session.post(url=url, json=data, headers=HEADERS).text)
                if res["code"] == 200:
                    # if self.query_todo_by_todo_id_info("activityDefId") == "":
                    #     print("完成宣贯环节：需要手动完成！")
                    #     break
                    print(
                        # f"计划名称：[{self.query_todo_by_todo_id_info("docName")}][{TODO_PLAN_ACTIVITY_DICT[self.query_todo_by_todo_id_info("activityDefId")]}]提交成功！")
                        f"计划名称：[{self.query_todo_by_todo_id_info("docName")}][{self.query_todo_by_todo_id_info("activityDefId")}]提交成功！")

                else:
                    print(res)
        else:
            print("没有获取到数据！")

    # 处理响应数据
    def query_todo_by_todo_id_info(self, search_value):
        if self.todo_by_todo_id:
            value = self.todo_by_todo_id["result"][search_value]
            return value

    # 根据todo查询任务详情信息
    def query_todo_by_todo_id(self):
        if self.todo_id:
            for todo in self.todo_id:
                url = urljoin(self.BASE_URL, f"bd-grsx-api/todo/queryTodoBytodoId/{todo}")
                res = json.loads(self.session.post(url=url, json="", headers=HEADERS).text)
                if res:
                    return res
                else:
                    return None

    # 获取下一步的节点
    # noinspection DuplicatedCode
    def get_next_plan_info(self):
        url = urljoin(self.BASE_URL, "zdgl-api/bxryStrategy/bxryNode")
        data = {"processdefId": self.query_todo_by_todo_id_info("processDefId"),
                "processdefName": self.query_todo_by_todo_id_info("processDefName"),
                "businessId": self.query_todo_by_todo_id_info("ywid"),
                "nodeId": self.query_todo_by_todo_id_info("activityDefId"), "xtbs": "10011006",
                "processInstId": self.query_todo_by_todo_id_info("processInstId"),
                "activityInstId": self.query_todo_by_todo_id_info("activityInstId")}
        res = json.loads(self.session.post(url=url, json=data, headers=HEADERS).text)
        # 检查是否成功返回和是否包含 "result" 键
        if res and "result" in res and res["result"]:
            return res["result"][0]["id"]
        else:
            # 处理请求失败或结果不符合预期的情况
            return None

    # 请求下一步节点
    def requests_next_plan(self):
        url = urljoin(self.BASE_URL, "zdgl-api/bxryStrategy/bxry")
        data = {"processdefId": self.query_todo_by_todo_id_info("processDefId"),
                "processdefName": self.query_todo_by_todo_id_info("processDefName"),
                "businessId": self.query_todo_by_todo_id_info("ywid"), "docType": "4", "xtbs": "10011006", "sqr": "",
                "sfwt": "2", "processInstId": self.query_todo_by_todo_id_info("parentProcessInstId"),
                "activityDefId": "",
                "activityInstId": "2081", "ywbs": "100",
                "nodeId": self.next_activit}
        res = json.loads(self.session.post(url=url, json=data, headers=HEADERS).text)
        return res


